#pragma once

#include <iostream>
#include <cstring>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

#define BACKLOG 8

using namespace LogModule;
using namespace ThreadPoolModule;

const static uint16_t gport = 8080;
using handler_t = std::function<std::string(std::string)>;

class TcpServer
{
    using task_t = std::function<void()>;
    struct ThreadData
    {
        int sockfd;
        TcpServer* self;
    };
public:
    TcpServer(handler_t handler, uint16_t port = gport)
    :_port(port)
    ,_isrunning(false)
    ,_handler(handler)
    {}

    void InitServer()
    {
        // 1.创建套接字
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "create socket success, sockfd is: " << _listensockfd;

        // 2.填充网络信息并绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = ::htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = ::bind(_listensockfd, CONV(&local), sizeof(local)); 
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd is: " << _listensockfd;

        // 3.设置套接字为监听状态
        n = ::listen(_listensockfd, BACKLOG);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error: " << strerror(errno);
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd is: " << _listensockfd;
    }

    void HandlerRequest(int sockfd)
    {
        LOG(LogLevel::INFO) << "HandlerRequest, sockfd is: " << sockfd;
        char inbuffer[4096];
        // 长任务
        while (true)
        {
            int n = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::string echo_string = "echo# ";
                echo_string += inbuffer;
                ::send(sockfd, echo_string.c_str(), echo_string.size(), 0);
                // std::string result = _handler(inbuffer);
                // ::send(sockfd, result.c_str(), result.size(), 0);
            }
            else if (n == 0)
            {
                // 当读到0，表明客户端退出了。
                LOG(LogLevel::INFO) << "client quit: " << sockfd;
                break;
            }
            else
            {
                // n < 0说明读取失败
                break;
            }
        }
        ::close(sockfd);
    }

    static void* ThreadEntry(void* args)
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        td->self->HandlerRequest(td->sockfd);
        delete td;        
        return nullptr;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            LOG(LogLevel::DEBUG) << "accept ing...";
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensockfd, CONV(&peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error: " << strerror(errno);
                continue;
            } 
            LOG(LogLevel::INFO) << "accept success, sockfd is: " << sockfd;
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "client info: " << "[" << addr.Addr() << "]";

            // version-0 单进程版
            // HandlerRequest(sockfd);
            
            // version-1 多进程版
            // pid_t id = fork();
            // if (id == 0)
            // {
            //     ::close(_listensockfd);
            //     if (fork() > 0) exit(0);
            //     HandlerRequest(sockfd);
            //     exit(0);
            // }
            // ::close(sockfd);
            // int rid = waitpid(id, nullptr, 0);  // 不会阻塞.
            // if (rid < 0)
            // {
            //     LOG(LogLevel::WARNING) << "waitpid error";
            // }

            // version-3 多线程版
            // pthread_t tid;
            // ThreadData* td = new ThreadData;
            // td->sockfd = sockfd;
            // td->self = this;
            // pthread_create(&tid, nullptr, ThreadEntry, td);

            // version-4 线程池版-比较适合处理短任务，或者是用户量少的情况
            // ThreadPool<task_t>::GetInstance()->Equeue(std::bind(&TcpServer::HandlerRequest, this, sockfd));
            ThreadPool<task_t>::GetInstance()->Equeue([this, sockfd](){
                this->HandlerRequest(sockfd);
            });
        }
    }

    void Stop()
    {
        _isrunning = false;
    }

    ~TcpServer()
    {

    }
private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;
    handler_t _handler;
};